package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Y1n
 * @date 2021/11/19 18:31
 * @decs
 **/
public class RequestProcessor extends Thread{

    private Socket socket;

    private Map<String,HttpServlet> servletMap ;

    private Mapper mapper;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {


        // 获取输入流
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();


            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            // 通过 判断 传过来的url 跟 servletMap 的key 是否存在
            // 如果存在说明是 动态资源 如果不存在说明是 静态资源
//            if(servletMap.get(request.getUrl()) != null){
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
//            }else {
//                response.outputHtml(request.getUrl());
//
//            }
            // minicat4 使用 传入的mapper来获取serlvet


            for (MapperHost mapperHost : mapper.getMapperHosts()) {
                for (MapperContext mapperContext : mapperHost.getMapperContexts()) {
                    for (MapperWrapper mappedWrapper : mapperContext.getMappedWrappers()) {
                        if(mappedWrapper.getUrl().equals(request.getUrl())){
                            HttpServlet httpServlet = mappedWrapper.getServlet();
                            httpServlet.service(request,response);
                        }else {
                            response.outputHtml(request.getUrl());

                        }
                    }
                }
            }

            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
